#pragma once
#include <iostream>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <cerrno>
#include <cstring>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <unordered_map>
#include "Thread.hpp"
#include "lockGuard.hpp"
#include "ringQueue.hpp"
#include "err.hpp"


namespace udp_server
{
    const static uint16_t default_port = 8080;
    using func_t = std::function<std::string(std::string)>;

    class UdpServer 
    {
    public:
        UdpServer(uint16_t port = default_port)
            :port_(port)
        {
            std::cout << "server addr: " << port_ << std::endl;
            pthread_mutex_init(&lock_, nullptr);
            p = new Thread(1, std::bind(&UdpServer::Recv, this));
            c = new Thread(1, std::bind(&UdpServer::Broadcast, this));
        }
        void start()
        {
            sock_ = socket(AF_INET, SOCK_DGRAM, 0);
            if (sock_ < 0)
            {
                std::cerr << "create socket error: " << strerror(errno) << std::endl;
                exit(SOCKET_ERR);
            }
            std::cout << "create socket success: " << sock_ << std::endl;
            
            struct sockaddr_in local;
            bzero(&local, 0);
            local.sin_family = AF_INET;
            local.sin_port = htons(port_);
            //local.sin_addr.s_addr = inet_addr(ip_.c_str());
            local.sin_addr.s_addr = INADDR_ANY;
            if (bind(sock_, (sockaddr*)&local, sizeof(local)) < 0)
            {
                std::cerr << "bind socket error: " << strerror(errno) << std::endl;
                exit(BIND_ERR);
            }
            std::cout << "bind socket success: " << sock_ << std::endl;

            p->run();
            c->run();
        }
        void addUser(const std::string& name, const struct sockaddr_in& peer)
        {
            LockGuard lockguard(&lock_);
            auto iter = onlineuser.find(name);
            if (iter != onlineuser.end()) return;
            onlineuser.insert(std::pair<const std::string, const struct sockaddr_in>(name, peer));
        }   
        void Recv()
        {
            while (true)
            {
                char buffer[1024];
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                int n = recvfrom(sock_, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&peer, &len);
                if (n > 0) buffer[n] = '\0';
                else continue;

                std::string clientip = inet_ntoa(peer.sin_addr);
                uint16_t clientport = ntohs(peer.sin_port);
                std::cout << clientip << "-" << clientport << "# " << buffer << std::endl;

                std::string name = clientip;
                name += "-";
                name += std::to_string(clientport);
                addUser(name, peer);
                std::string message = name + ">> " + buffer;
                rq.push(message);
                //std::string response = service_(buffer);

                //sendto(sock_, response.c_str(), response.size(), 0, (struct sockaddr*)&peer, sizeof(peer));
            }
        }
        void Broadcast()
        {
            while (true)
            {
                std::string sendstring;
                rq.pop(&sendstring);

                std::vector<struct sockaddr_in> v;

                {
                    LockGuard lockguard(&lock_);
                    for (auto user : onlineuser)
                    {
                        v.push_back(user.second);
                    }
                }

                for (auto user : v)
                {
                    sendto(sock_, sendstring.c_str(), sendstring.size(), 0, (struct sockaddr*)&user, sizeof(user));
                    std::cout << "send done..." << sendstring << std::endl;
                }
            }
        }
        ~UdpServer()
        {
            pthread_mutex_destroy(&lock_);
            p->join();
            c->join();

            delete p;
            delete c;
        }
    private:
        int sock_;
        uint16_t port_;
        //std::string ip_;
        //func_t service_;
        std::unordered_map<std::string, struct sockaddr_in> onlineuser;
        pthread_mutex_t lock_;
        RingQueue<std::string> rq;
        Thread* p;
        Thread* c;
    };
}